package com.example.cqcet_demo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.example.cqcet_demo.R;
import com.example.cqcet_demo.activity.HomeContentActivity;
import com.example.cqcet_demo.adapter.MyXlistViewHomeAdapter;
import com.example.cqcet_demo.bean.Page;
import com.example.cqcet_demo.widget.XListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Mr.z on 2017/6/19.
 */

public class HomeFragment extends Fragment {

    private View view;
    private XListView xListView;
    private MyXlistViewHomeAdapter mAdapter;
    private List<Page> items;
    private Handler mHandler;
    private int mIndex;
    private int mRefreshIndex;
    private OkHttpClient okHttpClient;
    private List<Page> refreshItems;

    private String url = "http://www.cqcet.edu.cn/";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(view==null) {
            view = inflater.inflate(R.layout.fragment_home, container, false);
            getData();
        }
        return view;
    }

    private void getData() {
        initView();
        mIndex = getActivity().getIntent().getIntExtra("pageNum",163);
        mRefreshIndex = getActivity().getIntent().getIntExtra("pageNum",163)+1;
        Log.d("mIndex",mIndex+"");
        items = (List<Page>) getActivity().getIntent().getSerializableExtra("items");
        //mAdapter = new ArrayAdapter<String>(getContext(), R.layout.vw_list_item, items);
        mAdapter = new MyXlistViewHomeAdapter(getContext(), this.items,xListView);
        xListView.setAdapter(mAdapter);
        xListView.setOnItemClickListener(new MyOnItemClickListener());

    }

    class MyOnItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String bodyData = items.get(position-1).getUrl();
            Intent intent = new Intent(getContext(), HomeContentActivity.class);
            intent.putExtra("bodyData",bodyData);
            startActivity(intent);
        }
    }

    private void getItems() {
        okHttpClient = new OkHttpClient();
        String items_url;
        if(mIndex == mRefreshIndex){
            refreshItems = new ArrayList<Page>();
            items_url = url +"index/xwdt.htm";
        }else{
            items_url = url + "index/xwdt/" + --mIndex+ ".htm";
        }

        Request res = new Request.Builder().url(items_url).get().build();
        try {
            Response rsp = okHttpClient.newCall(res).execute();
            if (rsp.isSuccessful()) {
                String data = rsp.body().string();
                Document doc = Jsoup.parse(data, "GBK");
                Elements htmlItems = doc.getElementsByClass("c50592");
                for (int i = 0; i < htmlItems.size(); i++) {
                    Element element = htmlItems.get(i);
                    String next_url = element.attr("href").replace("../../", "");
                    res = new Request.Builder().url(url + next_url).get().build();
                    rsp = okHttpClient.newCall(res).execute();
                    String body = rsp.body().string();
                    doc = Jsoup.parse(body, "GBK");

                    Page p = new Page();
                    p.setUrl(url + next_url);
                    p.setBody(body);

                    String page_id = next_url.split("/")[2].split("\\.")[0];
                    String num_url = "http://www.cqcet.edu.cn/system/resource/code/news/click/dynclicks.jsp?clickid=" + page_id + "&owner=1135322561&clicktype=wbnews";
                    res = new Request.Builder().url(num_url).get().build();
                    rsp = okHttpClient.newCall(res).execute();

                    p.setTitle(element.attr("title"));
                    Log.d("title", "title" + element.attr("title"));
                    p.setDate(doc.getElementById("article_extinfo").text().replace("]", rsp.body().string() + "]"));
                    Elements imgs = doc.select("div#article_body").select("img");
                    if(imgs.size()>0) {
                        String imgUrl = imgs.get(0).attr("src").replace("../../", url);
                        p.setImgUrl(imgUrl);
                    }
                    //Log.d("imgUrl", doc.getElementById("article_body").select("img").first().attr("src"));
                    Log.d("mIndex",mIndex+"");
                    Log.d("refreshmIndex",mRefreshIndex+"");
                    if(mIndex+1 == mRefreshIndex)
                        refreshItems.add(p);
                    else
                        items.add(p);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 0x11111:
                        xListView.setVisibility(View.GONE);
                        mAdapter.notifyDataSetChanged();
                        xListView.setVisibility(View.VISIBLE);
                        onLoad();
                        break;
                    case 0x11112:
                        Log.d("refresh.size",refreshItems.size()+"");
                        mAdapter = new MyXlistViewHomeAdapter(getContext(), refreshItems,xListView);
                        xListView.setAdapter(mAdapter);
                        items.clear();
                        items = new ArrayList<>(refreshItems);
                        onLoad();
                        break;
                }
            }
        };
        xListView = (XListView)view.findViewById(R.id.home_list);
        xListView.setPullRefreshEnable(true);
        xListView.setPullLoadEnable(true);
        xListView.setAutoLoadEnable(true);
        xListView.setXListViewListener(new MyxListViewLinstener());
        xListView.setRefreshTime(getTime());
    }

    private String getTime() {
        return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
    }

    class MyxListViewLinstener implements XListView.IXListViewListener{

        @Override
        public void onRefresh() {
            new Thread(){
                @Override public void run() {
                    mIndex = mRefreshIndex;
                    getItems();
                    Message message = new Message();
                    message.what=0x11112;
                    mHandler.sendMessage(message);

                }
            }.start();
        }

        @Override
        public void onLoadMore() {
            new Thread(){
                @Override public void run() {
                    getItems();
                    Log.d("itemsNum", mIndex + "");
                    Message message = new Message();
                    message.what=0x11111;
                    mHandler.sendMessage(message);

                }
            }.start();
        }
    }

    private void onLoad() {
        xListView.stopRefresh();
        xListView.stopLoadMore();
        xListView.setRefreshTime(getTime());
    }

}
